package com.gmail.bloim.serg.io;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Locale;

/**
 * User: Администратор
 * Date: 25.04.13
 * Time: 13:45
 */
public class ForkOutputStream extends OutputStream {

    private final OutputStream[] streams;

    public ForkOutputStream(OutputStream... streams) {
        this.streams = streams;
    }

    private ForkOutputStream(Collection<OutputStream> streams) {
        this.streams = streams.toArray(new OutputStream[streams.size()]);
    }

    @Override
    public void write(int b) throws IOException {
        for (OutputStream stream : streams) {
            try {
                stream.write(b);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void close() throws IOException {
        super.close();
        for(OutputStream stream : streams) {
            try {
                stream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static class Builder {
        private Collection<OutputStream> streams = new ArrayList<OutputStream>();

        public Builder add(OutputStream stream) {
            if (stream != null)
                streams.add(stream);
            return this;
        }

        public Builder add(Collection<OutputStream> streams) {
            if (streams != null)
                this.streams.addAll(streams);
            return this;
        }

        public ForkOutputStream build() {
            return new ForkOutputStream(streams);
        }
    }
}
